package org.yefei.homeworkday25;

import java.io.*;
import java.util.*;

public class Three {
	// 文件加密：
	public void jiaMi(String name) {
		InputStream i = null;
		OutputStream o = null;
		File file = new File("F:\\叶飞io测试\\IOhomework测试", name);
		File file2 = new File("F:\\叶飞io测试\\包装流", name);
		try {
			i = new FileInputStream(file);
			byte[] b = new byte[i.available()];
			o = new FileOutputStream(file2);
			int n = i.read(b);
			for (int j = 0; j < n; j++) {
				System.out.print(b[j]);
				o.write(~b[j]);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (o != null)
				try {
					o.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (i != null)
				try {
					i.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			boolean delete = file.delete();
			if (delete) {
				System.out.println("文件加密成功！");
			}
		}
	}

	// 文件解密
	public void jieMi(String name) {
		InputStream i = null;
		OutputStream o = null;
		File file = new File("F:\\叶飞io测试\\包装流", name);
		File file2 = new File("F:\\叶飞io测试\\IOhomework测试", name);
		try {
			i = new FileInputStream(file);
			byte[] b = new byte[i.available()];
			o = new FileOutputStream(file2);
			int n = i.read(b);
			for (int j = 0; j < n; j++) {
				System.out.print(b[j]);
				o.write(~b[j]);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (o != null)
				try {
					o.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (i != null)
				try {
					i.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			boolean delete = file.delete();
			if (delete) {
				System.out.println("文件解密成功！");
			}
		}

	}

	public static void main(String[] args) {
		/*
		 * 3：实现文件加密解密：加密规则是读出每一个字节，取反(~)后，写入 新文件，然后删除原文件，把新文件改成原文件同名的文件，
		 * 解密规则类似。输入一个文件名，实现加密和解密功能
		 */
		Three t = new Three();
		Scanner in = new Scanner(System.in);
		System.out.println("输入一个文件名：");
		String FileName = in.next();
		t.jiaMi(FileName);
		// t.jieMi(FileName);
	}

}
